package cn.chenfeifx.core.controls;

import cn.chenfeifx.core.layout.PopoverNode;
import javafx.geometry.Bounds;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;

/**
 * 文字提示
 */
public class CFTooltip extends CFPopover {

    private final Label textLabel;
    //
    private static final Color DARK_COLOR = Color.rgb(48, 49, 51, 0.8);
    private static final Color LIGHT_COLOR = Color.WHITE;

    public CFTooltip(Node owner, String text) {
        super(owner, new Label(text));
        textLabel = (Label) getPopoverNode().getContent();
        initialize();
    }

    public static CFTooltip create(Node owner, String text) {
        return create(owner, text, Effect.LIGHT, CFPopover.Pos.BOTTOM_CENTER);
    }

    public static CFTooltip create(Node owner, String text, Effect effect) {
        return create(owner, text, effect, CFPopover.Pos.BOTTOM_CENTER);
    }

    public static CFTooltip create(Node owner, String text, Effect effect, CFPopover.Pos pos) {
        CFTooltip tooltip = new CFTooltip(owner, text);
        PopoverNode popoverNode = tooltip.getPopoverNode();
        switch (effect) {
            case DARK -> {
                popoverNode.setFill(DARK_COLOR);
                popoverNode.setStroke(Color.TRANSPARENT);
                tooltip.textLabel.setTextFill(Color.WHITE);
            }
            case LIGHT -> {
                popoverNode.setFill(LIGHT_COLOR);
                popoverNode.setStroke(Color.rgb(0, 0, 0, 0.45));
            }
        }
        tooltip.setPos(pos); // 位置
        return tooltip;
    }

    private void initialize() {
        textLabel.setPadding(new Insets(8)); // padding
        textLabel.setFont(Font.font(13)); // 字体大小
        textLabel.setWrapText(true); // 自动换行
        textLabel.setMaxSize(300, Region.USE_PREF_SIZE); // 最大宽度
        // 鼠标移入移出显示和隐藏
        getOwner().addEventHandler(MouseEvent.MOUSE_ENTERED, event -> super.show());
        getOwner().addEventHandler(MouseEvent.MOUSE_EXITED, event -> {
            Bounds layoutBounds = getOwner().getLayoutBounds();
            if (!layoutBounds.contains(event.getX(), event.getY())) { // 验证鼠标位置不在ownerNode范围内再隐藏
                super.hide();
            }
        });
    }

    public void setText(String text) {
        textLabel.setText(text);
    }

    public String getText() {
        return textLabel.getText();
    }

    public void setGraphic(Node graphic) {
        textLabel.setGraphic(graphic);
    }

    public enum Effect {
        DARK, LIGHT
    }

}
